package permission

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"gorm.io/gorm"
)

type permissionRepository struct {
	tenant_db.TenantDB
}

// NewPermissionRepository 构造函数
func NewPermissionRepository() PermissionRepositoryIface {
	return &permissionRepository{}
}

// PermissionListByMenuIds 获取菜单下的权限列表
func (r *permissionRepository) PermissionListByMenuIds(ctx context.Context, menuIds []int64) ([]*GfyxPermission, error) {
	db := r.GetTenantDB(ctx)
	list := make([]*GfyxPermission, 0)
	err := db.Where("is_deleted = ?", constants.IsDeletedFalse).
		Where("gfyx_menu_id in (?)", menuIds).
		Find(&list).Error
	return list, err
}

// PermissionListByIds 获取权限列表
func (r *permissionRepository) PermissionListByIds(ctx context.Context, ids []int64) ([]*GfyxPermission, error) {
	db := r.GetTenantDB(ctx)
	list := make([]*GfyxPermission, 0)
	err := db.Where("is_deleted = ?", constants.IsDeletedFalse).
		Where("id in (?)", ids).
		Find(&list).Error
	return list, err
}

// GetPermissionByUserId 获取用户的权限列表
func (r *permissionRepository) GetPermissionByUserId(ctx context.Context, userId int64) ([]*GfyxPermission, error) {
	gfyxPermission := make([]*GfyxPermission, 0)
	db := r.GetTenantDB(ctx)
	err := db.Table("gfyx_user_role_relation A").
		Joins("left join gfyx_role_permission_relation B on A.role_id = B.role_id").
		Joins("left join gfyx_permission C on B.permission_id = C.id").
		Where("A.user_id =?", userId).
		Where("A.is_deleted =?", constants.IsDeletedFalse).
		Where("B.is_deleted =?", constants.IsDeletedFalse).
		Where("C.is_deleted =?", constants.IsDeletedFalse).
		Select("C.*").
		Find(&gfyxPermission).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return gfyxPermission, nil
}
